/**
 * @description Ccay XTab
 */
//Ccay.UI.XTab = {};
(function(Tab){
	// set defalut config
	var config = {
	        itemMaxCount : 10, //限制tabItem最大数
	        // CSS
	        tabCSS:"ccay-tab",
	        tabLinkCSS: "tab-link",
	        tabUlCSS : "tab-ul",
	        tabContentCSS: "tab-content",
	        tabContenItemCSS:"tab-content-item",
	        tabItemCloseBtnCSS:"tab-item-close",
	        tabLeftBtnCSS:"nav-btn left-btn",
	        tabRightBtnCSS:"nav-btn right-btn",
	        tabSelectedItemCSS:"tab-selected"
	};
	//define control flow
	var flow = {
		init:function(tab, op){
		   tab.dom.addClass(op.tabCSS).addClass("l-tab");
		   op.width && tab.dom.width(op.width);
		   op.height && tab.dom.height(op.height);
		},
		build:function(tab, op){
		   ccayTab.buildBody(tab, op);
		},
		bindEvent:function(tab, op){
		   ccayTab.eventBinder(tab, op);
		},
		complete:function(tab, op){
			// 指定defaultItemId或者html指定selected属性
			var selectedItem = tab.dom.find(".tab-content-item[selected]:first");
			if(op.defaultItemId || selectedItem.length){ //是否指定默认选中的tab页的tabId
			    tab.selectItem(op.defaultItemId || selectedItem.attr("tabid"));
			}else{
				tab.selectItem(tab.getItems().first().attr("tabid"));
			};
			tab.moveItem("toFirst");
		}
	};
	//define control manager
	var manager = {
		getPanelLink: function(){
	        return DomClass.getProp(this, this.dom, "panelLink", "." + this.op.tabLinkCSS);
	    },
	    getPanelDiv:function(){
	    	return DomClass.getProp(this, this.getPanelLink(), "panelDiv", "div");
	    },
	    getPanelUl: function(){
	        return DomClass.getProp(this, this.getPanelDiv(), "panelUl", "." + this.op.tabUlCSS);
	    },
	    // 获得项对象
	    getItems: function(){
	    	return this.getPanelUl().children("li");
	    },
	    // 根据tabId获得项对象
	    getItemByTabId : function(tabId){
	    	return this.getPanelUl().children("li[tabid=" + tabId + "]");
	    },
	    // 获得已选择的项对象
	    getSelectedItem : function(){
	    	return this.getPanelUl().children("."+this.op.tabSelectedItemCSS);
	    },
	    // 获得内容对象
		getContent: function(){
            return DomClass.getProp(this, this.dom, "tabContent", "." + this.op.tabContentCSS);
        },
        // 获得项内容对象
        getContentItem : function(tabId){
	    	return this.getContent().children("." + this.op.tabContenItemCSS + "[tabid=" + tabId + "]");
	    },
	    // 获得可移动按钮对象
	    getNavButton : function(){
	    	//return DomClass.getProp(this, this.getPanelLink(), "navButton", ".nav-btn");
	    	return this.getNavButtonContainer().children(".nav-btn");
	    },
	    getNavButtonContainer : function(){
	    	return this.getPanelLink().children(".tab-nav-btn");
	    },
	    // reload项内容
	    reloadItem : function(tabId, op){
	    	this.getItemByTabId(tabId).children("a").html($i18n(op.title));
	    	
	        op.url && this.getContentItem(tabId).ccayLoad(op.url, op.fnAfterAddItem, true);
	    },
	    // 是否确认关闭tab项
	    isConfirm2Close : function(item){
			var me = this, tabId = item.attr("tabid");
			if(item.attr('isConfirm')){
				Ccay.UI.confirm("ccay.tab.tabitem.confirm2close", function(yesBtn){
							if(yesBtn){
								me.confirmRemoveItem(tabId);
							}
						})
			}else{
				me.confirmRemoveItem(tabId);
			}
		},
		// 添加项
		addItem : function(itemOp){
			var currentItem = this.addItemOnly(itemOp);
			if(currentItem && itemOp.selected !== false){
				this.selectItem(currentItem.attr("tabid"));
				this.setItemVisiable(currentItem);
			}
			this.setNavButton();
			this.getNavButton().removeClass("disabled");
			
			// 增加addItemAtAfter属性
			if(itemOp.addItemAtAfter){
				currentItem.insertAfter($("li[tabid='"+itemOp.addItemAtAfter+"']"));
			}
		},
		// 添加项
		addItemOnly : function(itemOp){
			var me = this, tabId = itemOp.tabId || itemOp.tabIndex, currentItem , helperTip=itemOp.helperTip;;
			// 无tabId时，由系统生成
			if(tabId == null){
				tabId = "_tabitem" + (this.op._tempTabItemCount + 1);
			};
			// before事件
			if(this.op.fnBeforeAddItem && this.op.fnBeforeAddItem.call(this, tabId) === false){
				return false;
			}
	        // 若存在相同的tabId的tabitem，则更新此tabitem，否则新添加tabitem
	        if(me.isItemExist(tabId)){
	        	if(itemOp.isOpenConfirm == true){ //是否配置了覆盖确认操作，默认不提示confirm
	        		Ccay.UI.confirm("ccay.tab.tabitem.add.warn",
	        				function(yesBtn){
	        			          if(yesBtn){
	        			        	  me.reloadItem(tabId,itemOp);
	        			          }
    			          	}, true )
	        	}else{
	        		me.reloadItem(tabId,itemOp);
	        	};
	        }else{
	        	// 判断是否超过最大tab数目
	        	if(this.getItemCount() + 1 > this.op.itemMaxCount){
					Ccay.UI.showMessage($i18n("ccay.tab.tabitem.maxcount.warn").formatValue(this.op.itemMaxCount),"warn");
					return;
				};
				
				this.op._tempTabItemCount ++;
	        	var tabItem , closeByConfirm;
	        	var title = $i18n(itemOp.title || itemOp.text);
	        	if(!itemOp.closeByConfirm){
	        		closeByConfirm= "";
	        	}else{
	        		closeByConfirm = "isConfirm=" + itemOp.closeByConfirm;
	        	};
	        	// 默认显示关闭按钮，除非指定不显示
	        	if(itemOp.showClose == null || itemOp.showClose){
	        		tabItem = "<li tabid={0} {1}><a>{2}</a><div class='{3}'></div></li>".formatValue(tabId, closeByConfirm , title, this.op.tabItemCloseBtnCSS);
	        	}else{
	        		tabItem = "<li tabid={0} {1}><a>{2}</a></li>".formatValue(tabId, closeByConfirm , title);
	        	};
	        	if(itemOp.addItemAtAfter){
	        		this.getPanelUl().find("[tabid='"+itemOp.addItemAtAfter+"']").after(tabItem);
	        	}else {
		        	this.getPanelUl().append(tabItem);
	        	}
	        	if(helperTip){
	        	 	this.getPanelUl().find("[tabid='"+tabId+"'] a").attr("id",helperTip);
	        	    var locationUrl = location.href.split("#!")[1]||"";
	        	        locationUrl && Ccay.Component.InfoTip.init(locationUrl);
	        	 }
	        	
	        	
		       // this.getPanelUl().append(tabItem);
				var contentItem = $.create("div", this.op.tabContenItemCSS).attr("tabid", tabId);
				this.getContent().append(contentItem.hide());
				// 可指定"content",若有url,则覆盖content
				itemOp.content &&  contentItem.html(itemOp.content);
				itemOp.url && contentItem.ccayLoad(itemOp.url, itemOp.fnAfterAddItem, true);
		    }
	        // after事件
	        this.op.fnAfterAddItem && this.op.fnAfterAddItem.call(this, tabId);
	        
	        return this.getItemByTabId(tabId);
		},
		// 使选择的tab页可见
		setItemVisiable : function(item){
	        var currentItemLeft = item.position().left,
	        	tabWidth = this.dom.width(),
	        	currentUl = this.getPanelUl(),
	        	currentItemWidth = item.width();
	        
        	if(currentItemLeft + currentItemWidth > tabWidth){
        		//currentUl.animate({left: -(currentItemLeft + currentItemWidth - tabWidth + 24)});
        		currentUl.animate({left: - (currentUl.width() - tabWidth + 24)});
        	}else{
        		currentUl.animate({left: 0});
        	}
		},
		// 移除tab项
		removeItem : function(tabId){
			var me = this, selectedItem;
			// 是否存在tabid，否则得到当前选择的tab的tabid
			if(!tabId){
				selectedItem = this.getSelectedItem();
				tabId = selectedItem.attr('tabid');
			}
			// before事件
			if(me.op.fnBeforeRemoveItem && me.op.fnBeforeRemoveItem.call(this, tabId) === false){
	       		return false;
	        };
	        // 关闭确认
	        var item =  selectedItem ? selectedItem : me.getItemByTabId(tabId);
        	me.isConfirm2Close(item);
        	
			me.op.fnAfterRemoveItem && me.op.fnAfterRemoveItem.call(this, tabId);
		},
		// 经确认移除tab项
		confirmRemoveItem : function(tabId){
	        var targetItem = this.getItemByTabId(tabId);
	        var targetContent = this.getContentItem(tabId);
	        // 如果是当前选中的项，则判断是否有前一个项则选中，否则选中后一个；
	        if(targetItem.hasClass(this.op.tabSelectedItemCSS)){
	        	targetItem.prev().length ? this.selectPrevItem() : this.selectNextItem();
	        }
	        // 模块卸载
	        if(targetContent.attr("module"))
				Ccay.Module.remove(targetContent.attr("module"));
	        targetContent.remove();
	        targetItem.remove();
	        this.setNavButton();
		},
		// 根据tabId判断是否存在tab项
	    isItemExist : function(tabId){
	        return this.getItemByTabId(tabId).length > 0;
		},
		// 选中tab项
		selectItem : function(tabId){
			var op = this.op;
			if(op.fnBeforeSelectItem && op.fnBeforeSelectItem.call(this, tabId) === false){
	       		return;
	        }
			var existItem = this.getItemByTabId(tabId);
			if(existItem.length){
				var currentContent = this.getContentItem(tabId),
					currentUrl = existItem.attr("url");
				currentContent.show().siblings().hide();
	        	existItem.addClass("l-selected " + op.tabSelectedItemCSS).siblings().removeClass("l-selected " + op.tabSelectedItemCSS);
	        	// 点击一次事件,若已点击选中，则return
		        if(op.fnOnceSelectItem && !existItem.hasClass("once-loaded")){
		        	op.fnOnceSelectItem.call(this, tabId);
		        	existItem.addClass("once-loaded");
		        }
	        	// 加载url页面
	        	if(currentUrl && !existItem.hasClass("url-loaded")){
					currentContent.ccayLoad(currentUrl, null, true);
					existItem.addClass("url-loaded");
				}
				
			}else{
				return;
			}
			op.fnAfterSelectItem && op.fnAfterSelectItem.call(this, tabId);
		},
		// 选中前一个tab项
		selectPrevItem : function(){
			var prevItem = this.getSelectedItem().prev();
			prevItem.length && this.selectItem(prevItem.attr("tabid"));	
		},
		
		// 命名兼容
		movePrev : function(){this.selectPrevItem()},
		moveNext : function(){this.selectNextItem()},
		moveLast : function(){this.moveItem("toLast")},
		
		// 选中后一个tab项
		selectNextItem : function(){
			var nextItem = this.getSelectedItem().next();
			nextItem.length && this.selectItem(nextItem.attr("tabid"));	
		},
		// 设置可移动按钮是否可见并绑定事件
		setNavButton : function(){
			var me  = this;
			setTimeout(function(){
		        var sumWidth = me.getPanelUl().width(),
		        	tabWidth = me.dom.width();
		        // 超出范围时添加按钮，否则移除
		        if(sumWidth + 16 > tabWidth){
		            // 只添加一次，绑定事件一次
		            if(me.getNavButtonContainer().length == 0){
		            	// 防止item移动不了
		            	//me.getPanelUl().css("position", "relative");
		            	me.getPanelUl().addClass("tab-hasnav");
		            	me.getPanelLink().append("<div class='tab-nav-btn'><div class='{0}'></div><div class='{1}'></div></div>".formatValue(me.op.tabLeftBtnCSS, me.op.tabRightBtnCSS));
		            	me.getPanelLink().delegate(".nav-btn","click",function(){
		            		$(this).hasClass(me.op.tabLeftBtnCSS) 
		            		? me.moveItem("toPrev") 
		            		: me.moveItem("toNext");
				        });
		            };
		        }else{
		            me.getPanelUl().animate({ left: 0 }).removeClass("tab-hasnav");
		            me.getNavButtonContainer().remove();
		        }
	        },100);
		},
		// 获得已选择的tab项的tabId
		getSelectedItemId : function(){
			return this.getSelectedItem().attr("tabid");
		},
		// 获得tab项的数目
		getItemCount : function(){
			return this.getItems().length;
		},
		// 移动tab ,method包含toPrev，toNext，toFirst，toLast
		moveItem : function(method){
			this.setNavButtonEvent(method);
		},
		// 往前移动一个tab项的宽度 
		// !!!如下四个方法已由moveItem代替
		moveToPrevItem : function(){
			this.setNavButtonEvent("toPrev");
		},
		// 往后移动一个tab项的宽度
		moveToNextItem : function(){
			this.setNavButtonEvent("toNext");
		},
		// 往前移动到第一个tab项的宽度
		moveToFirstItem : function(){
			this.setNavButtonEvent("toFirst");
		},
		// 往后移动到最后一个tab项的宽度
		moveToLastItem : function(){
			this.setNavButtonEvent("toLast");
		},
		// 设置按钮事件
		setNavButtonEvent : function(type){
			var ul = this.getPanelUl(),
			 	tabItems = this.getItems(),
				// 按钮的width
	        	btnWidth = this.getNavButton().width(),
	        	// tabItem的总长
	        	sumWidth = ul.width(),
	        	// 得到tab的长度
	       	 	tabWidth = this.dom.width(),
	        	// 记录每个tab的left,由右到左
	        	leftList = new Array(), 
	        	// 当前item的left
	        	currentItemLeft, 
	        	// 当前的link区的left
	        	currentLinkLeft = -1 * parseInt(ul.css("left")),
	        	// 左右按钮
	        	navBtn = this.getNavButton(),
	        	leftNavBtn = $(navBtn[0]),
	        	rightNavBtn = $(navBtn[1]);
	        switch(type){
	        	case "toFirst":
	        	    ul.animate({left: 17});
	        	    leftNavBtn.addClass("disabled");
	        	    rightNavBtn.removeClass("disabled");
	        		break;
	        	case "toLast":
			        if(sumWidth > tabWidth){
			        	  ul.animate({ left: -1 * (sumWidth - tabWidth + btnWidth)});
			        	  rightNavBtn.addClass("disabled");
			        	  leftNavBtn.removeClass("disabled");
			        };
	        	    break;
	        	case "toPrev":
		        	currentItemLeft = -1 * btnWidth;
		        	if(leftNavBtn.hasClass("disabled")){
		        		break;
		        	};
			        tabItems.each(function(i){
			        	var currentItem  = $(this);
			            if(i > 0){
			                currentItemLeft = parseInt(leftList[i - 1]) + currentItem.prev().width() + 3*i;
			            }
			            leftList.push(currentItemLeft);
			        });
			        var prevFlag = false, toLeftWidth = 0;
			        for(var i = 0; i < leftList.length - 1; i++){
			        	var flag = leftList[i] < currentLinkLeft && leftList[i + 1] >= currentLinkLeft;
			        	if(flag){
			        		i == 0 &&　(prevFlag = true);
			        		toLeftWidth = leftList[i];
			        		break;
			        	}
			        };
			        
			        if (flag) {
						ul.animate({left : -1 * parseInt(toLeftWidth)});
						rightNavBtn.hasClass("disabled") && rightNavBtn.removeClass("disabled");
					}
					if (prevFlag) {
						leftNavBtn.addClass("disabled");
					}
			        break;
	        	case "toNext":
		        	currentItemLeft = sumWidth - tabWidth + btnWidth;
		        	if(rightNavBtn.hasClass("disabled")){
		        		break;
		        	};
			        for(var i = tabItems.length - 1; i >= 0; i--){
			            if(i != tabItems.length - 1){
			                currentItemLeft = parseInt(leftList[tabItems.length - 2 - i]) - $(tabItems[i + 1]).width() - 2;
			            }
			            leftList.push(currentItemLeft);
			        };
			        var nextFlag = false, toRightWidth = 0;
			        for(var j = 1; j < leftList.length; j++){
			        	var flag = (leftList[j] <= currentLinkLeft) && (leftList[j - 1] > currentLinkLeft);
			        	if(flag){
			        		j == 1 && (nextFlag = true);
			        		toRightWidth = (leftList[j - 1]);
			        		break;
			        	};
			        };
			        
			        if(flag){
		                ul.animate({left: -1 * (parseInt(toRightWidth) + leftList.length * 1)});
		            	leftNavBtn.hasClass("disabled") && leftNavBtn.removeClass("disabled");
		            }
		            
			        if(nextFlag){
			        	rightNavBtn.addClass("disabled");
			        }
			        break;
	        };
		}
	};
	
	// 命名,兼容老版本
	$.fn.getCcayTabManager = $.fn.manager ;
	
	// 关闭Tab
	// @param {Number} index:tab项的序号，从0开始算，默认为当前tab项
	$.fn.ccayTabRemoveItem = function(index) {
		if (this.length == 0) {
			return;
		};
		var selector = index ? ':eq(' + index + ')' : 'li.tab-selected';
		var tabId = this.find('.tab-link').find('.tab-ul ' + selector).attr('tabid');
		this.getCcayTabManager().removeItem(tabId);
		// 由于 removeItem 阻止了事件冒泡，导致下拉框不能正确关闭，需要重新触发全局click
		$(document.body).click();
		return this;
	};
	
	//create XControl
	var XTab = Ccay.UI.XControl("XTab",flow,config,manager);
	
	// create jquery plugin
	$.fn.ccayTab = function(op){
		return this.each(function(){
			// 只能初始化一次
			if(!$(this).hasClass("ccay-tab") || !$(this).hasClass("l-tab")){
				new XTab($(this), op);
			}
		})
	};
	
	var ccayTab = {
		// 构建html
		buildBody : function(tab, op){
		    var closeBtn, tabHeader = [];
			// 创建link和content区对象
			tab.dom.append('<div class="{0}"><div class="link-container"><ul class="{1}"></ul></div></div><div class="{2}"></div>'
				   .formatValue(op.tabLinkCSS + " l-tab-links", op.tabUlCSS, op.tabContentCSS));
			// tabitem数目
			var items = tab.dom.children("div[title]");
			op._tempTabItemCount =  items.length ;
			if(items.length > op.itemMaxCount){
				Ccay.UI.showMessage($i18n("ccay.tab.tabitem.maxcount.warn").formatValue(op.itemMaxCount),"warn");
				return;
			}
			var getContent = tab.getContent().addClass("l-tab-content");
			items.each(function(i){
				var itemdiv = $(this),
					title = $i18n(itemdiv.attr("title")),
					url = itemdiv.attr("url"),
					tabId = itemdiv.attr("tabid");
		        if(tabId == null){
		        	tabId = "_tabitem" + (i+1);
		        };
		        if(String(itemdiv.attr("showClose")) == "true"){
		        	closeBtn = "<div class='{0}'></div>".formatValue(op.tabItemCloseBtnCSS);
		        }else{
		        	closeBtn = "";
		        };
		        tabHeader.push('<li tabid="', tabId ,url ? '" url="' + url + '"':'"', ' ><a ',itemdiv.attr("helperTip")?'id="'+itemdiv.attr("helperTip")+'"':'','>', title ,'</a>', closeBtn , '</li>');
		        // 生成内容区
		        var item = itemdiv.addClass(op.tabContenItemCSS).addClass("l-tab-content-item").attr("tabid", tabId).removeAttr("title");
		        getContent.append(item);
		    });
		    // 生成tab导航区
		    tab.getPanelUl().append(tabHeader.join(""));
		    // 定义按钮是否显示
		    tab.setNavButton();
		},
		// 绑定元素事件
		eventBinder : function(tab, op){
			// 分开绑定事件，由于close按钮在li内，点击close时导致触发两次click
			tab.getPanelUl().delegate("li","click", function(e){
				var target = $(e.target);
				if(!target.hasClass(op.tabItemCloseBtnCSS)){
					tab.selectItem(target.attr("tabid") || target.parent().attr("tabid"));
				}
			});
			tab.getPanelUl().delegate("."+ op.tabItemCloseBtnCSS,"click", function(e){
				var target = $(e.target);
				tab.removeItem(target.parent().attr("tabid"));
			});
		}
	}	
	
})(Ccay.UI.XTab);